from flask import  Flask, render_template,request,escape
import requests
import matplotlib.pyplot as plt
import json
from weatherapi import weather

app = Flask(__name__)


def log_request(req: "flask request", res: str):
    print(req.form)
    print(req.host_url)
    print(req.remote_addr)
    with open("vsearch.log", "a") as log:
        print(req.form, req.host_url, req.remote_addr, file=log, sep="|")


# @app.route('/search',methods = ['POST'])
# def search():
# 	phrase = request.form.get("phrase")
# 	letters = request.form.get("letters")
# 	results=phrase+letters
# 	log_request(request,results)
# 	title = "Here are your results"
# 	return render_template("results.html",the_title=title,the_phrase=phrase,the_letters=letters,the_results=results)

@app.route('/home', methods=['post', 'get'])
def hello_entry():
    user = request.form.get("user")
    log_request(request, user)
    return render_template('home.html', the_title='图片识别网')


@app.route("/login", methods=['get'])
def index() -> 'html':
    return render_template("login.html", )


@app.route("/remote", methods=["POST",'GET'])
def remote():
    if request.method=="POST":

        image_url = request.form['remote']
        endpoint = "https://cvhzx.cognitiveservices.azure.com/"
        subscription_key = "236e247ef32e4f61a71202de77cb8266"
        analyze_url = endpoint + "vision/v3.1/analyze"
        headers = {'Ocp-Apim-Subscription-Key': subscription_key}
        params = {'visualFeatures': 'Categories,Description,Color'}
        data = {'url': image_url}
        response = requests.post(analyze_url, headers=headers, params=params, json=data)
        response.raise_for_status()
        analysis = response.json()
        image_caption = analysis["description"]["captions"][0]["text"].capitalize()
        confidence3 = analysis["description"]["captions"][0]["confidence"]
        return render_template('remote.html', remote=str(image_caption), confidence3=str(confidence3), img_url1=image_url)
    return render_template("remote.html")



@app.route("/items", methods=["POST","GET"])
def items():
    if request.method=="POST":

        image_url = request.form["items"]
        landmark_analyze_url = 'https://cvhzx.cognitiveservices.azure.com/' + "vision/v3.1/models/landmarks/analyze"
        subscription_key = '7388368827d942c5b517d8c6218ef191'
        headers = {'Ocp-Apim-Subscription-Key': subscription_key}
        params = {'model': 'landmarks'}
        data = {'url': image_url}
        response = requests.post(
            landmark_analyze_url, headers=headers, params=params, json=data)
        response.raise_for_status()
        analysis = response.json()
        assert analysis["result"]["landmarks"] is not []
        print(analysis)
        landmark_name = analysis["result"]["landmarks"][0]["name"].capitalize()
        confidence = analysis["result"]["landmarks"][0]["confidence"]
        print(confidence)
        print(image_url)
        return render_template('items.html', items=str(landmark_name), confidence1=str(confidence), img_url2=image_url)
    return render_template("items.html")



@app.route("/person", methods=["POST","GET"])
def person():
    if request.method=="POST":
        image_url = request.form["person"]
        subscription_key = "7388368827d942c5b517d8c6218ef191"
        assert subscription_key
        vision_base_url = "https://cvhzx.cognitiveservices.azure.com/vision/v2.1/"
        celebrity_analyze_url = vision_base_url + "models/celebrities/analyze"
        headers = {'Ocp-Apim-Subscription-Key': subscription_key}
        params = {'model': 'celebrities'}
        data = {'url': image_url}
        response = requests.post(celebrity_analyze_url, headers=headers, params=params, json=data)
        response.raise_for_status()
        analysis = response.json()
        celebrity_name = analysis["result"]["celebrities"][0]["name"].capitalize()
        confidence2 = analysis["result"]["celebrities"][0]["confidence"]
        return render_template('person.html', person=str(celebrity_name), confidence2=str(confidence2), img_url3=image_url)
    else:
        return render_template('person.html')


@app.route("/we", methods=["post",'get'])
def we():

    key = '18ef7dd6aeefc21dade574262c00f213'
    city = '440100'
    extensions = 'base'
    a = weather(key, city, extensions)
    b = a['lives'][0]['city']
    c = a['lives'][0]['weather']
    d = a['lives'][0]['temperature']
    return render_template('weather.html', city=str(b), weather=str(c), temperature=str(d))

@app.route("/log", methods=["post",'get'])
def log():
    data=[]
    with open("vsearch.log","r") as f:
        info_list=f.readlines()
        for i in info_list:
            data.append(i.split("|"))

    return render_template('log.html',data=data)


if __name__ == '__main__':
    app.run(debug=True)

